package com.yihu.wlyy.web.patient.sign;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.yihu.wlyy.entity.SignWeb;
import com.yihu.wlyy.service.app.sign.SignWebService;
import com.yihu.wlyy.web.BaseController;

@RequestMapping(value = "/patient/sign")
@RestController
public class PatientSignController extends BaseController {

	@Autowired
	private SignWebService signWebService;

	/**
	 * 个人医生签约
	 * @param patient 患者标识
	 * @param doctor 医生标识
	 * @param status 签约状态(0待签约，1已拒绝，2已签约，3患者申请取消签约，4医生申请取消签约，5已解约)
	 * @param startTime 签约开始时间
	 * @param endTime 到期时间
	 * @return 申请结果
	 */
	@RequestMapping("/sign_doctor")
	public String signDoctor(@RequestParam(value = "doctor") String doctor, 
			@RequestParam(value = "startTime", required = false) String startTime, 
			@RequestParam(value = "endTime", required = false) String endTime) {
		try {
			List<Object> listDoctor = signWebService.getSignInfoByStatus(getUID());
			if (listDoctor.size() > 0) {
				return error(-1, "存在已签约的医生,请确认!");
			}

			Page<Object> list = signWebService.getSignInfoByPatient(getUID(), 0, 0, 15);
			if (list.getTotalPages() > 0) {
				return error(-1, "已存在申请签约的医生,请确认!");
			}

			String errorMsg = "";
			if (StringUtils.isEmpty(doctor)) {
				errorMsg = "医生代码不能为空!";
			}
			
			if (StringUtils.isNotEmpty(errorMsg)) {
				return error(-1, errorMsg);
			}

			SignWeb signWeb = new SignWeb();
			signWeb.setUser(getUID());
			signWeb.setDoctor(doctor);
			signWeb.setStatus(0);
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			if (!StringUtils.isEmpty(startTime)) {
				Date beginDate = format.parse(startTime);
				signWeb.setBeginDate(beginDate);
			}
			if (!StringUtils.isEmpty(endTime)) {
				Date endDate = format.parse(endTime);
				signWeb.setEndDate(endDate);
			}
			// 操作人（1患者，2医生）
			signWeb.setOper(1);
			signWeb.setApplyDate(new Date());
			boolean result = signWebService.saveSignWeb(signWeb);
			if (!result) {
				return error(-1, getResultMsg(result, 0));
			}

			return success(getResultMsg(result, 0));
		} catch (Exception ex) {
			error(ex);
			return error(-1, "系统错误,请联系管理员!");
		}

	}

	/**
	 * 修改家庭签约状态
	 * @param code 签约标识
	 * @param status 签约状态(0待签约，1已拒绝，2已签约，3患者申请取消签约，4医生申请取消签约，5已解约)
	 * @return
	 */
	@RequestMapping("/update_status")
	public String updateSignWeb(@RequestParam(value = "code") String code, 
			@RequestParam(value = "status") int status, 
			@RequestParam(value = "startDate", required = false) String startDate, 
			@RequestParam(value = "endDate", required = false) String endDate) {
		try {
			SignWeb signWeb = signWebService.getSignWebByCode(code);
			if (signWeb == null) {
				return error(-1, "签约记录不存在!");
			}

			signWeb.setStatus(status);
			if (StringUtils.isNotEmpty(startDate)) {
				if (StringUtils.isEmpty(endDate)) {
					return error(-1, "到期时间不能为空!");
				}

				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
				Date beginDate = format.parse(startDate);
				signWeb.setBeginDate(beginDate);
				Date endDateTime = format.parse(endDate);
				signWeb.setEndDate(endDateTime);
			}
			signWeb.setApplyDate(new Date());
			boolean result = signWebService.saveSignWeb(signWeb);
			if (!result) {
				return error(-1, getResultMsg(result, status));
			}

			return success(getResultMsg(result, status));
		} catch (Exception ex) {
			error(ex);
			return error(-1, "系统错误,请联系管理员!");
		}
	}

	/**
	 * 返回操作提醒
	 * @param result 操作结果
	 * @param status 签约状态
	 * @return
	 */
	public String getResultMsg(boolean result, int status) {
		String msg = "申请成功!";
		switch (status) {
		case 0:
			if (!result) {
				msg = "申请失败!";
			}
			break;
		case 1:
			msg = "已拒绝申请!";
			if (!result) {
				msg = "拒绝失败!";
			}
			break;
		case 2:
			msg = "签约成功!";
			if (!result) {
				msg = "签约失败!";
			}
			break;
		case 3:
		case 4:
			msg = "申请解约成功!";
			if (!result) {
				msg = "申请解约失败!";
			}
			break;
		case 5:
			msg = "解约成功!";
			if (!result) {
				msg = "解约失败!";
			}
			break;
		case 6:
			msg = "取消成功!";
			if (!result) {
				msg = "取消失败!";
			}
			break;
		}

		return msg;
	}

	/**
	 * 获取签约医生信息  状态未传查全部签约信息
	 * @param status 签约状态 (0待签约，1已拒绝，2已签约，3患者申请取消签约，4医生申请取消签约，5已解约)
	 * @param query 查询条件 (医生姓名)
	 * @return
	 */
	@RequestMapping("/sign_info")
	public String getSignInfo(@RequestParam(required = false) String status, @RequestParam(defaultValue = "0") long id, int pageSize) {
		try {
			int iStatus = 0;
			if (StringUtils.isEmpty(status)) {
				iStatus = -1;
			} else {
				iStatus = Integer.parseInt(status);
			}

			Page<Object> listSign = signWebService.getSignInfoByPatient(getUID(), iStatus, id, pageSize);

			JSONArray jsonArray = new JSONArray();
			if (listSign != null) {
				for (Object obj : listSign) {
					Object[] temp = (Object[]) obj;
					if (temp == null) {
						continue;
					}
					JSONObject json = new JSONObject();
					json.put("code", temp[0]);
					json.put("patientCode", temp[1]);
					json.put("doctorCode", temp[2]);
					json.put("doctorName", temp[3]);
					json.put("hosptialName", temp[4]);
					json.put("deptName", temp[5]);
					json.put("jobName", temp[6]);
					iStatus = (Integer) temp[7];
					json.put("status", iStatus);
					json.put("photo", temp[8]);
					switch (iStatus) {
					case 0:
						status = "待签约";
						break;
					case 1:
						status = "已拒绝";
						break;
					case 2:
						status = "已签约";
						break;
					case 3:
					case 4:
						status = "申请解约";
						break;
					case 5:
						status = "已解约";
						break;
					case 6:
						status = "已取消";
						break;
					}
					json.put("statusName", status);
					json.put("id", temp[9]);

					jsonArray.put(json);
				}
			}

			return write(200, "查询成功！", "list", jsonArray);
		} catch (Exception ex) {
			return error(-1, "系统错误,请联系管理员!");
		}
	}
}
